package com.kfm.ajax.controller;

import com.kfm.ajax.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@CrossOrigin("*")
public class TestController {

    @Autowired
    RedisTemplate<String, String> redisTemplate;


    @RequestMapping({"/register", "/"})
    public String index() {
        return "test";
    }
    //
    // get?username=
    @RequestMapping("/get")
    @ResponseBody
    public Result get(String username) {
        // request.getParameter("username")
        // TODO 查询用户名是否已经存在
        // 取值
        String s = redisTemplate.opsForValue().get("1");
        System.out.println(s);
        // 设置值
        redisTemplate.opsForValue().set("1", "pomelo");
        System.out.println(username);
        if ("root".equals(username)) {
            return Result.failure("用户名已经存在");
        }
        return Result.success("用户名可以使用！","good");
    }

    @RequestMapping("/send")
    @ResponseBody
    public Result sendMsg(String phone) {
        // TODO 发送短信验证码
        // TODO key 加密
        // 将用户的电话作为key 验证码作为value 存储到redis中 过期时间是 5分钟
        redisTemplate.opsForValue().set(phone, "123456", 5, TimeUnit.MINUTES);
        System.out.println(phone);
        return Result.success("发送验证码成功");
    }

    @RequestMapping("/verify")
    @ResponseBody
    public Result verifyCode(String phone, String code) {
        String s = redisTemplate.opsForValue().get(phone);
        if (s != null && s.equals(code)) {
            return Result.success("验证码正确");
        }
        return Result.failure("验证错误！");
    }

    @GetMapping("/getAge")
    @ResponseBody
    public Result getAge() {
        return Result.success("成功", 20);
    }

    @GetMapping("/getP")
    @ResponseBody
    public Result getPublicKey() {
        // TODO 获取一对公私钥
        String privateKey = "private";
        String publicKey = "public";
        String uuid = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(uuid, privateKey);
        Map<String, String> map = new HashMap<>();
        map.put("public", publicKey);
        map.put("uuid", uuid);
        return Result.success("success", map);
    }

    @PostMapping("/login")
    @ResponseBody
    public Result login(String username, String password, String uuid) {
        String privateKey = redisTemplate.opsForValue().get(uuid);
        // TODO 使用私钥对数据解密，解密之后操作数据库查询是否可以登录
        String user = username;
        return Result.success("登录成功", user);
    }
}
